package com.code.fileserver.controller;

import com.code.fileserver.utils.Accest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@RestController
public class UploadController {
    @Value("${fileserver.base-path}")
    private String bathPath;

    @RequestMapping(value = "/upload")
    public Object upload(@RequestParam("file")MultipartFile file, HttpServletRequest request) {
        Accest.isTrue(file.isEmpty(),"文件为空");
        String prefix = request.getParameter("prefix");
        if(StringUtils.isEmpty(prefix)){
            prefix="default";
        }
        return baseUpload(Arrays.asList(file),prefix).get(0);
    }

    private List<String> baseUpload(List<MultipartFile> multipartFiles, String prefix) {
        List<String> list = new ArrayList<>();
        String format = DateTimeFormatter.ofPattern("/YYYY/MM/DD/").format(LocalDateTime.now());
        String path = bathPath +prefix+ format;
        File file1 = new File(path);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        for (MultipartFile file : multipartFiles) {
            String newName = format+ UUID.randomUUID().toString()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            // 真实路径
            String p = bathPath +prefix+ newName;
            File f = new File(p);
            try {
                file.transferTo(f);
            } catch (IOException e) {
                e.printStackTrace();
            }
            list.add(prefix+newName);
        }
        return list;
    }
}
